package cn.com.playerlyric.krc;

import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.File;

import cn.com.lyric.krc.KrcView;
import cn.com.playerlyric.R;

public class KrcActivity extends AppCompatActivity {

    //歌词显示控件
    private KrcView krcView;
    //播放器
    private MediaPlayer mediaPlayer;
    //文件根目录，存放图片、音乐和krc歌词
    private String mDir = Environment.getExternalStorageDirectory()+ File.separator + "openkrc" + File.separator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_krc);
        krcView = (KrcView) findViewById(R.id.krcView);
        // 歌词路径
        String krcPath = mDir + "一克拉的眼泪.krc";
        try {
            krcView.setKrcPath(krcPath);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            mediaPlayer=MediaPlayer.create(this, R.raw.ykl);
            mediaPlayer.setOnPreparedListener(new PreparedListener());
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        mediaPlayer.stop();
    }

    private class PreparedListener implements MediaPlayer.OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 当歌曲还在播放时
                    // 就一直调用changeCurrent方法
                    // 虽然一直调用， 但界面不会一直刷新??有时候会有跳帧情况，求大神指点
                    while (mediaPlayer.isPlaying()) {
                        // 调用changeCurrent方法， 参数是当前播放的位置
                        // KrcView会自动判断需不需要下一行
                        krcView.changeCurrent(mediaPlayer.getCurrentPosition());
                        // 当然这里还是要睡一会的啦,
                        //??时间设置长一点不会出现跳帧
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
}
